package dao;

import entity.User;
import utils.DBHelper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class UserDao implements BaseDao<User> {
    private static  final String TABLENAME = "t_user" ;

    @Override
    public boolean add(User u) {
        String SQL = "INSERT INTO "+TABLENAME+"values(?,?,?,?,?,?)";

        return DBHelper.execute(SQL,u.getUserId(),u.getRealName(),u.getGender(),u.getTel(),u.getAddress(),u.getPassword());

    }

    public boolean updatePassword(User u) {
        String SQL = "UPDATE "+TABLENAME+"set PASSWORD ='"+u.getPassword()+"' WHERE TEL = '"+u.getTel()+"'";
        System.out.println(SQL);
        return DBHelper.execute(SQL);
    }

    @Override
    public boolean delete(User o) {
        return false;
    }

    @Override
    public boolean update(User u) {

        String SQL = "UPDATE "+TABLENAME+"set realname = ? , gender = ? ,address = ? where tel = ?";
        return DBHelper.execute(SQL, u.getRealName(), u.getGender(),u.getAddress(),u.getTel());

    }

    @Override
    public List<User> loadAll() {
        return null;
    }

    /**
     * 根据用户名查询用户信息
     * @param realName 用户名
     * @return 返回一个用户对象
     */
    public User loadByRealName (String realName){
        User user = null ;
        return user ;
    }

    public  User loadBytel(String tel){
        User u = null;
        String SQL = "select realname,gender,address,password,tel from "+TABLENAME+" where tel = ?";

        ResultSet rs = DBHelper.query(SQL,tel);
        u = wrap(rs);
        return u;
    }

    /**
     * 包装数据到一个对象中
     * @param rs 结果集
     * @return 返回一个用户对象
     */
    public User wrap (ResultSet rs) {
        User u = null;
        try {
            if (rs.next()) {
                u = new User();
                u.setRealName(rs.getString("realname"));
                u.setGender(rs.getString("gender"));
                u.setAddress(rs.getString("address"));
                u.setPassword(rs.getString("password"));
                u.setTel(rs.getString("tel"));
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return u;
    }
}
